package com.example.jwt.config;

import com.example.jwt.filter.security.JwtLoginFilter;
import com.example.jwt.filter.security.JwtTokenFilter;
import com.example.jwt.handler.security.JwtAccessDeniedHandler;
import com.example.jwt.handler.security.JwtAuthenticationEntryPoint;
import com.example.jwt.handler.security.JwtLoginFailureHandler;
import com.example.jwt.handler.security.JwtLoginSuccessHandler;
import com.example.jwt.service.JwtUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
    }

    @Autowired
    private JwtLoginSuccessHandler loginSuccessHandler;
    @Autowired
    private JwtLoginFailureHandler failureHandler;
    @Autowired
    private JwtAccessDeniedHandler jwtAccessDeniedHandler;

    @Autowired
    private JwtFilterInvocationSecurityMetadataSource filterInvocationSecurityMetadataSource;
    @Autowired
    private JwtUrlAccessDecisionManager urlAccessDecisionManager;
    @Autowired
    private JwtAuthenticationEntryPoint authenticationEntryPoint;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 自定义的登陆拦截器
        JwtLoginFilter jwtLoginFilter = new JwtLoginFilter();
        jwtLoginFilter.setAuthenticationManager(authenticationManagerBean());
        jwtLoginFilter.setAuthenticationSuccessHandler(loginSuccessHandler);
        jwtLoginFilter.setAuthenticationFailureHandler(failureHandler);

        // 自定义的登录验证器
        JwtAuthenticationProvider jwtAuthenticationProvider = new JwtAuthenticationProvider(jwtUserDetailsService, passwordEncoder());

        // 自定义访问资源拦截器
        JwtTokenFilter jwtTokenFilter = new JwtTokenFilter(jwtUserDetailsService);


        http.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setSecurityMetadataSource(filterInvocationSecurityMetadataSource);
                        object.setAccessDecisionManager(urlAccessDecisionManager);
                        return object;
                    }
                })
                .and()
                .authorizeRequests().antMatchers("/login.html").permitAll()
                .antMatchers(HttpMethod.POST, "/login").permitAll()
                // 使用 JWT 情况下, 匿名好像没有用..
                .antMatchers("/anonymous").anonymous()
                .and()
                .authorizeRequests().anyRequest().authenticated();

        // 禁用默认的登陆
        http.formLogin().disable();


        //
        http.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .csrf().disable()
                .authenticationProvider(jwtAuthenticationProvider)
                .addFilterBefore(jwtLoginFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterAfter(jwtTokenFilter, JwtLoginFilter.class);

        // 权限校验异常处理
        http.exceptionHandling()
                .accessDeniedHandler(jwtAccessDeniedHandler)
                .authenticationEntryPoint(authenticationEntryPoint);
    }

}
